TOPNAME = top
NXDC_FILES = ./constr/top.nxdc
INC_PATH ?= 
VERILOG_INC_PATH = $(abspath ./vsrc)

VERILATOR = verilator
# flags for vcd 
VERILATOR_VCDFLAGS = --cc --exe --build -j 0 -Wall --trace
# flags for nvboard 
VERILATOR_CFLAGS += -MMD --build -cc  \
				-O3 --x-assign fast --x-initial fast --noassert

# directories or files for nvboard
BUILD_DIR = ./build
OBJ_DIR = $(BUILD_DIR)/obj_dir
BIN = $(BUILD_DIR)/$(TOPNAME)

# directories or files for vcd
VBUILD_DIR = ./vbuild
VOBJ_DIR = $(VBUILD_DIR)/obj_dir
VBIN = $(VBUILD_DIR)/$(TOPNAME)

# find vcd file
VCD = $(shell find $(abspath ./) -maxdepth 2 -name "*.vcd")

all: $(BIN) $(VBIN)

$(shell mkdir -p $(BUILD_DIR))
$(shell mkdir -p $(VBUILD_DIR))

# constraint file
SRC_AUR_BIND = $(abspath $(BUILD_DIR)/auto_pin_bind.cpp)
$(SRC_AUR_BIND): $(NXDC_FILES)
	python3 $(NVBOARD_HOME)/scripts/auto_pin_bind.py $^ $@

# project source
VSRCS = $(shell find $(abspath ./vsrc) -name "*.sv")
CSRCS = $(shell find $(abspath ./csrc) -name "*.cpp")
CSRCS += $(SRC_AUR_BIND)
VCSRCS = $(shell find $(abspath ./vcsrc) -name "*.cpp")

# rules for NVBoard
include $(NVBOARD_HOME)/scripts/nvboard.mk

# rules for verilator
# TIMESCALE = 1ns/1ns
INCFLAGS = $(addprefix -I, $(INC_PATH))
CXXFLAGS += $(INCFLAGS) -DTOP_NAME="\"V$(TOPNAME)\""

$(BIN): $(VSRCS) $(CSRCS) $(NVBOARD_ARCHIVE)
	@rm -rf $(OBJ_DIR)
	$(VERILATOR) $(VERILATOR_CFLAGS) \
		--top-module $(TOPNAME) $^ \
		$(addprefix -CFLAGS , $(CXXFLAGS)) $(addprefix -LDFLAGS , $(LDFLAGS)) \
		--timing -I$(VERILOG_INC_PATH) --Mdir $(OBJ_DIR) --exe -o $(abspath $(BIN))

$(VBIN): sim

sim: $(VSRCS) $(VCSRCS) 
	$(call git_commit, "sim RTL") # DO NOT REMOVE THIS LINE!!!
	@rm -rf $(VOBJ_DIR)
	$(VERILATOR) $(VERILATOR_VCDFLAGS) \
		--top-module $(TOPNAME) $^ \
		--Mdir $(VOBJ_DIR) -o $(abspath $(VBIN))

vcd: $(VBIN) 
	@$^


wave: $(VCD)	
	gtkwave $^

run: $(BIN)
	@$^


clean:
	rm -rf $(BUILD_DIR)

.PHONY: all sim vcd VCD run clean

include ../../Makefile
